﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using ElingOA6_Admin_DSJCJ.Models;
using DevExpress.Web.Mvc;
using System.Data;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 相册类别管理
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class AlbumClsManageController : AdminBaseController
    {
        //
        // GET: /Admin/AlbumClsManage/

        /// <summary>
        /// 相册类别BLL
        /// </summary>
        private BLL.AlbumCls albumClsBLL = new BLL.AlbumCls();
        /// <summary>
        /// 相册类别权限BLL
        /// </summary>
        private BLL.AlbumAuth albumAuthBLL = new BLL.AlbumAuth();
        /// <summary>
        /// 部门BLL
        /// </summary>
        private BLL.HRDept hrDeptBLL = new BLL.HRDept();
        /// <summary>
        /// 用户BLL
        /// </summary>
        private BLL.PrvUser prvUserBLL = new BLL.PrvUser();
        /// <summary>
        /// 岗位逻辑类
        /// </summary>
        private BLL.HRPosition hrPositionBLL = new BLL.HRPosition();
        /// <summary>
        /// 人员岗位逻辑类
        /// </summary>
        private BLL.HREmplPosition hrEmplPositionBLL = new BLL.HREmplPosition();
        /// <summary>
        /// 相册类别管理首页
        /// </summary>
        /// <returns>视图</returns>
        [AuthorityActionFilter("m_AlbumClsManage", Order = 1)]
        [LogPageActionFilter("相册类别管理", Order = 2)]
        public ActionResult Index(string focusNodeName = "")
        {
            ViewData["focusNodeName"] = focusNodeName;
            string where = "";
            List<Model.AlbumCls> albumClsList = albumClsBLL.GetModelList(where);
            ViewData["isHaveTreeData"] = albumClsList.Count == 0 ? false : true;
            return View();
        }
        /// <summary>
        /// 相册类别树
        /// </summary>
        /// <param name="focusNodeName"></param>
        /// <returns></returns>
        public ActionResult AlbumClsTree(string focusNodeName = "")
        {
            string where = "";
            List<Model.AlbumCls> albumClsList = albumClsBLL.GetModelList(where);
            ElingOA6_Admin_DSJCJ.Models.TreeModelList treeModelList = new TreeModelList();
            if (albumClsList.Count > 0)
            {
                foreach (Model.AlbumCls albumClsModel in albumClsList)
                {
                    TreeItemModel treeParentItemModel = new TreeItemModel(null)
                    {
                        Id = DevExpressHelper.GetUrl(new { Controller = "AlbumClsManage", Action = "EditAlbumCls" }) + "|" + albumClsModel.FAlbumClsNo,
                        Name = albumClsModel.FAlbumClsName,
                        ImageUrl = Url.Content("~/Content/ControlImages/user_group.png")
                    };
                    treeModelList.Add(treeParentItemModel);
                }
            }
            ViewData["focusNodeName"] = focusNodeName;
            return View(treeModelList);
        }
        /// <summary>
        /// 增加相册类别
        /// </summary>
        /// <returns>返回增加相册类别视图</returns>
        public ActionResult AddAlbumCls()
        {
            //return AddGroup("", null);
            return EditAlbumCls("0", "", "ADD_SAME", new Model.AlbumCls());
        }
        /// <summary>
        /// 修改相册类别
        /// </summary>
        /// <param name="groupID"相册类别编码</param>
        /// <returns>返回修改相册类别视图</returns>
        public ActionResult EditAlbumCls(string albumClsNo)
        {
            return EditAlbumCls(albumClsNo, "", "EDIT", null);
        }

        /// <summary>
        /// 删除相册类别
        /// </summary>
        /// <returns>删除后所显示信息</returns>
        [HttpPost]
        public string DeleteAlbumCls(string albumClsNo)
        {
            string jsonstr = "FAILED";
            string errorMessage = "错误";
            if (albumClsNo != "")
            {
                try
                {
                    albumClsBLL.DeleteAlbumCls(albumClsNo, GlobalConstant.ENTITYNO);
                    jsonstr = "SUCCESS";
                }
                catch
                {
                    errorMessage = "操作异常";
                }
                if (jsonstr == "FAILED")
                {
                    jsonstr += "FAILED|" + errorMessage;
                }
            }
            return jsonstr;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="prvGroupModel">用户组信息</param>
        /// <returns>返回用户组保存后视图</returns>
        public ActionResult Save()
        {
            bool isSuccess = true;
            Model.AlbumCls albumClsModel = new Model.AlbumCls();
            string errorMessage = "";
            ActionResult actionResult = null;


            if (Fetch.Post("txtFAlbumClsNo") == "")
            {
                errorMessage = "相册类别编码不能为空";
                isSuccess = false;
            }
            else
            {
                albumClsModel.FAlbumClsNo = Fetch.Post("txtFAlbumClsNo");
            }
            //数据逻辑验证
            if (Fetch.Post("txtFAlbumClsName") == "")
            {
                errorMessage = "相册类别名称不能为空";
                isSuccess = false;
            }
            else
            {
                albumClsModel.FAlbumClsName = Fetch.Post("txtFAlbumClsName");
            }

            string users = Fetch.Post("hdOrgUserSelect");
            List<string> orgUserList = new List<string>();
            if (users != "")
            {
                orgUserList = users.Split(new char[1] { ',' }).ToList();
            }
            string entityNo = GlobalConstant.ENTITYNO;
            switch (Fetch.Post("hdMethod"))
            {
                case "ADD_SAME":
                    {
                        if (albumClsBLL.Exists(albumClsModel.FAlbumClsNo))
                        {
                            errorMessage = "相册类别编码已存在";
                            isSuccess = false;
                        }
                        else
                        {
                            try
                            {
                                albumClsBLL.AddAlbumCls(albumClsModel, orgUserList, entityNo);
                                //增加成功
                                ViewData["focusKey"] = DevExpressHelper.GetUrl(new { Controller = "AlbumClsManage", Action = "EditAlbumCls" }) + "|" + albumClsModel.FAlbumClsNo;//焦点定位的节点ID
                                ViewData["methodFromType"] = Fetch.Post("hdMethod");
                                ViewData["nodeText"] = albumClsModel.FAlbumClsName;
                                actionResult = View("SuccessMessageByTree");
                            }
                            catch
                            {
                                errorMessage = "操作异常:";
                                isSuccess = false;
                            }
                        }
                        if (actionResult == null)
                        {
                            actionResult = EditAlbumCls("", errorMessage, Fetch.Post("hdMethod"), new Model.AlbumCls());
                        }
                        break;
                    }
                case "EDIT":
                    {
                        if (isSuccess)
                        {
                            try
                            {
                                albumClsBLL.EditAlbumCls(albumClsModel, orgUserList, entityNo);
                                //修改成功
                                ViewData["RedirectURL"] = Url.Action("EditAlbumCls", "AlbumClsManage", new { albumClsNo = albumClsModel.FAlbumClsNo });
                                ViewData["methodFromType"] = Fetch.Post("hdMethod");
                                ViewData["nodeText"] = albumClsModel.FAlbumClsName;
                                actionResult = View("SuccessMessageByTree");
                            }
                            catch
                            {
                                errorMessage = "操作异常:";
                            }
                        }
                        if (actionResult == null)
                        {
                            actionResult = EditAlbumCls(albumClsModel.FAlbumClsNo, errorMessage, Fetch.Post("hdMethod"), albumClsModel);
                        }
                        break;
                    }
            }

            return actionResult;
        }

        #region 私有方法
        /// <summary>
        /// 修改相册类别
        /// </summary>
        /// <param name="groupID">相册类别编码</param>
        /// <param name="jsAlert">显示文字</param>
        /// <param name="methodType">页面类型  ADD_SAME 新增; EDIT 修改</param>
        /// <param name="albumClsModel">相册类别数据</param>
        /// <returns>返回增加或修改相册类别视图</returns>
        private ActionResult EditAlbumCls(string albumClsNo, string jsAlert, string methodType, Model.AlbumCls albumClsModel)
        {
            string entityNo = GlobalConstant.ENTITYNO;
            List<Model.HRPosition> hrPositionList = hrPositionBLL.GetListByEntityNo(entityNo);
            DataTable emplDT = hrEmplPositionBLL.GetMainDeptEmplALL(entityNo);

            //增加和修改同一个页面
            ViewData["hdMethod"] = methodType;//类型  ADD_SAME 新增; EDIT 修改
            if (albumClsModel == null)
            {
                albumClsModel = albumClsBLL.GetModel(albumClsNo);
            }
            if (albumClsModel != null)
            {
                List<string> emplNoList = new List<string>();
                if (methodType == "EDIT")
                {

                    emplNoList = albumAuthBLL.GetEmplNoListByAlbumClsNo(albumClsNo, GlobalConstant.ENTITYNO); //当前相册类别权限的所有成员
                }
                List<Model.HRDept> hrDeptList = hrDeptBLL.GetListNoNameByEntityNo(GlobalConstant.ENTITYNO);

                string treeJsonStr = "";
                treeJsonStr += "[";
                if (hrDeptList == null)
                {
                    hrDeptList = hrDeptBLL.GetListByEntityNo(entityNo);
                }
                if (hrDeptList.Count > 0)
                {
                    Dictionary<int, List<Model.HRDept>> dicHRDeptList = new Dictionary<int, List<Model.HRDept>>();
                    if (GlobalConstant.ENTITYNO == "05")
                    {
                        //鄞州财政
                        //局机关
                        dicHRDeptList.Add(0, hrDeptList.Where(s => s.FIsAgency == "N").OrderBy(s => s.FDeptNo).ToList());
                        //派出机构(镇乡街道)
                        dicHRDeptList.Add(1, hrDeptList.Where(s => s.FIsAgency == "Y").OrderBy(s => s.FDeptNo).ToList());

                    }
                    else
                    {
                        dicHRDeptList.Add(0, hrDeptList);
                    }
                    foreach (KeyValuePair<int, List<Model.HRDept>> dicDept in dicHRDeptList)
                    {
                        if (dicHRDeptList.Count == 1)
                        {
                            treeJsonStr += "{'title':'组织结构','key':'-1','expand':true,'isFolder':true,'activate':true";
                            treeJsonStr += ",'children':[";
                        }
                        else
                        {

                            if (dicDept.Key == 0)
                            {
                                treeJsonStr += "{'title':'局机关','key':'-1','expand':true,'isFolder':true,'activate':true";
                                treeJsonStr += ",'children':[";

                            }
                            else
                            {
                                if (dicDept.Value.Count > 0)
                                {
                                    treeJsonStr += "{'title':'镇乡街道','key':'-1','expand':true,'isFolder':true,'activate':true";
                                    treeJsonStr += ",'children':[";
                                }
                            }
                        }
                        List<Model.HRDept> keyHRDeptList = dicDept.Value;
                        foreach (Model.HRDept hrDeptModel in keyHRDeptList)
                        {
                            List<Model.HRDept> tmpChildDeptList = keyHRDeptList.Where(s => s.FParentDeptNo == hrDeptModel.FDeptNo).ToList();
                            int childCount = tmpChildDeptList.Count;
                            if (childCount > 0)
                            {
                                treeJsonStr += "{'title':'" + hrDeptModel.FDeptName + "','key':'" + hrDeptModel.FDeptNo + "','expand':false,'isFolder':true,'activate':true,'icon':'" + Url.Content("~/Content/ControlImages/dept_Groups.png") + "'";
                                treeJsonStr += ",'children':[";
                                GetChildHRDept(tmpChildDeptList, ref treeJsonStr, keyHRDeptList, hrPositionList, emplDT, emplNoList);
                                //绑定部门
                                if (hrPositionList != null)
                                {
                                    List<Model.HRPosition> tmpPositionList = hrPositionList.Where(c => c.FDeptNo == hrDeptModel.FDeptNo).ToList();
                                    if (tmpPositionList.Count > 0)
                                    {
                                        treeJsonStr += ",";
                                        GetPostion(tmpPositionList, ref treeJsonStr);

                                    }
                                }
                                //绑定人员
                                if (emplDT != null)
                                {
                                    var tmpEmp = (from c in emplDT.AsEnumerable()
                                                  where c["FDeptNo"].ToString() == hrDeptModel.FDeptNo
                                                  select c);
                                    if (tmpEmp.Count() > 0)
                                    {
                                        DataTable tmpEmplDT = tmpEmp.CopyToDataTable();
                                        treeJsonStr += ",";
                                        GetEmpl(tmpEmplDT, ref treeJsonStr, emplNoList);
                                    }

                                }
                                treeJsonStr += "]";

                            }
                            else
                            {
                                treeJsonStr += "{'title':'" + hrDeptModel.FDeptName + "','key':'" + hrDeptModel.FDeptNo + "','expand':false,'isFolder':false,'activate':true,'icon':'" + Url.Content("~/Content/ControlImages/dept_Groups.png") + "'";
                                //绑定部门
                                if (hrPositionList != null)
                                {
                                    List<Model.HRPosition> tmpPositionList = hrPositionList.Where(c => c.FDeptNo == hrDeptModel.FDeptNo).ToList();
                                    if (tmpPositionList.Count > 0)
                                    {
                                        treeJsonStr += ",'children':[";
                                        GetPostion(tmpPositionList, ref treeJsonStr);
                                        treeJsonStr += "]";
                                    }
                                }
                                //绑定人员
                                if (emplDT != null)
                                {
                                    var tmpEmp = (from c in emplDT.AsEnumerable()
                                                  where c["FDeptNo"].ToString() == hrDeptModel.FDeptNo
                                                  select c);
                                    if (tmpEmp.Count() > 0)
                                    {
                                        DataTable tmpEmplDT = tmpEmp.CopyToDataTable();
                                        treeJsonStr += ",'children':[";
                                        GetEmpl(tmpEmplDT, ref treeJsonStr, emplNoList);
                                        treeJsonStr += "]";
                                    }
                                }

                            }
                            treeJsonStr += "},";
                        }
                        if (keyHRDeptList.Count > 0)
                        {
                            treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
                            treeJsonStr += "]";
                            treeJsonStr += "},";
                        }
                    }
                    treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
                    treeJsonStr += "]";

                }
                else
                {
                    //treeJsonStr += "{'title':'组织结构','key':'-1','expand':true,'isFolder':false,'activate':true";
                    treeJsonStr += "]";
                }

                //treeJsonStr += "},";
                //treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
                //treeJsonStr += "]";
                treeJsonStr = treeJsonStr.Replace("\\", "");
                treeJsonStr = treeJsonStr.Replace("'", "\"");
                ViewData["treeJsonStrOrgUser"] = treeJsonStr;
                //隐藏字段

                ViewData["jsAlert"] = jsAlert;
                ViewData["albumClsNo"] = albumClsNo;

                return View("EditAlbumCls", albumClsModel);
            }

            return null;
        }

        /// <summary>
        /// 递归获取子部门
        /// </summary>
        /// <param name="hrDeptChildList">子部门列表</param>
        /// <param name="treeJsonStr">json树的字符串</param>
        /// <param name="hrDeptList">全部部门列表</param>
        /// <param name="emplDT">全部人员DT</param>
        private void GetChildHRDept(List<Model.HRDept> hrDeptChildList, ref string treeJsonStr, List<Model.HRDept> hrDeptList, List<Model.HRPosition> hrPositionList, DataTable emplDT, List<string> emplNoList)
        {
            foreach (Model.HRDept tmpDeptModel in hrDeptChildList)
            {
                List<Model.HRDept> tmpChildDeptList = hrDeptList.Where(s => s.FParentDeptNo == tmpDeptModel.FDeptNo).ToList();

                int childCount = tmpChildDeptList.Count;
                if (childCount > 0)
                {
                    treeJsonStr += "{'title':'" + tmpDeptModel.FDeptName + "','key':'" + tmpDeptModel.FDeptNo + "','expand':false,'isFolder':true,'activate':true";
                    treeJsonStr += ",'children':[";
                    GetChildHRDept(tmpChildDeptList, ref treeJsonStr, hrDeptList, hrPositionList, emplDT, emplNoList);
                    //绑定部门
                    if (hrPositionList != null)
                    {
                        List<Model.HRPosition> tmpPositionList = hrPositionList.Where(c => c.FDeptNo == tmpDeptModel.FDeptNo).ToList();
                        if (tmpPositionList.Count > 0)
                        {
                            treeJsonStr += ",";
                            GetPostion(tmpPositionList, ref treeJsonStr);

                        }
                    }
                    //绑定人员
                    if (emplDT != null)
                    {
                        var tmpEmp = (from c in emplDT.AsEnumerable()
                                      where c["FDeptNo"].ToString() == tmpDeptModel.FDeptNo
                                      select c);
                        if (tmpEmp.Count() > 0)
                        {
                            DataTable tmpEmplDT = tmpEmp.CopyToDataTable();
                            treeJsonStr += ",";
                            GetEmpl(tmpEmplDT, ref treeJsonStr, emplNoList);
                        }

                    }
                    treeJsonStr += "]";

                }
                else
                {
                    treeJsonStr += "{'title':'" + tmpDeptModel.FDeptName + "','key':'" + tmpDeptModel.FDeptNo + "','expand':false,'isFolder':false,'activate':true,'icon':'" + Url.Content("~/Content/ControlImages/dept_Groups.png") + "'";
                    //绑定部门
                    if (hrPositionList != null)
                    {
                        List<Model.HRPosition> tmpPositionList = hrPositionList.Where(c => c.FDeptNo == tmpDeptModel.FDeptNo).ToList();
                        if (tmpPositionList.Count > 0)
                        {
                            treeJsonStr += ",'children':[";
                            GetPostion(tmpPositionList, ref treeJsonStr);
                            treeJsonStr += "]";
                        }
                    }
                    //绑定人员
                    if (emplDT != null)
                    {
                        var tmpEmp = (from c in emplDT.AsEnumerable()
                                      where c["FDeptNo"].ToString() == tmpDeptModel.FDeptNo
                                      select c);
                        if (tmpEmp.Count() > 0)
                        {
                            DataTable tmpEmplDT = tmpEmp.CopyToDataTable();
                            treeJsonStr += ",'children':[";
                            GetEmpl(tmpEmplDT, ref treeJsonStr, emplNoList);
                            treeJsonStr += "]";
                        }
                    }

                }
                treeJsonStr += "},";
            }
            treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
        }
        /// <summary>
        /// 绑定岗位树岗位数据
        /// </summary>
        /// <param name="hrPositionDeptList">该部门岗位列表</param>
        /// <param name="treeJsonStr">json树的字符串</param>
        private void GetPostion(List<Model.HRPosition> hrPositionDeptList, ref string treeJsonStr)
        {
            foreach (Model.HRPosition hrPositionModel in hrPositionDeptList)
            {
                treeJsonStr += "{'title':'" + hrPositionModel.FPositionName + "','key':'" + hrPositionModel.FPositionNo + "','expand':false,'isFolder':false,'activate':true,'icon':'" + Url.Content("~/Content/ControlImages/mail_post_to.png") + "','addClass':'position'";
                treeJsonStr += "},";
            }
            treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
        }
        /// <summary>
        /// 绑定人员树数据
        /// </summary>
        /// <param name="emplDeptDT">该部门人员DT</param>
        /// <param name="treeJsonStr">json树的字符串</param>
        private void GetEmpl(DataTable emplDeptDT, ref string treeJsonStr, List<string> emplNoList)
        {
            foreach (DataRow dr in emplDeptDT.Rows)
            {
                treeJsonStr += "{'title':'" + dr["FEmpName"].ToString() + "','key':'" + dr["FEmplNo"].ToString() + "','expand':false,'isFolder':false,'activate':true,'icon':'" + Url.Content("~/Content/ControlImages/user_male.png") + "','addClass':'user'";
                if (emplNoList.Contains(dr["FEmplNo"].ToString()))
                {
                    treeJsonStr += ",'select':true";
                }
                treeJsonStr += "},";
            }
            treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
        }
        #endregion
    }
}
